<template>
  <div>
    <!-- 面包屑 -->
    <breadcrumb
      :breadcrumbArr="jsList.breadcrumbArr"
      :breadcrumbLastItem="breadcrumbLastItem"
      :state="state"
      @handleBack="handleBack"
    />
    <div v-if="isTrue" class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs v-model="activeName" class="el-tabs__customize">
          <el-tab-pane label="基本信息" name="first">
            <baseInfo ref="baseInfo" :detail="detailInfo" />
          </el-tab-pane>

          <el-tab-pane label="采购清单" name="second">
            <purchaseList ref="purchaseList" :detail="detailInfo" />
          </el-tab-pane>

          <el-tab-pane label="附件" name="third">
            <uploadInfo ref="uploadInfo" :detail="detailInfo" :state="state" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle(3)"
            >暂存</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle(0)"
            >保存并校验</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle(1)"
            >保存并提交</el-button
          >
        </li>
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回</el-button
          >
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import { mapActions, mapGetters } from "vuex";
import jsList from "../js";
import baseInfo from "./baseInfo";
import purchaseList from "./purchaseList";
import publicComponent from "@/basa/components/public";
import uploadInfo from "./uploadInfo.vue";
import {
  getInventory,
  tsInventory,
  savInventory,
  editInventory,
  checkStockIsChange
} from "../api";
export default {
  props: {
    state: {
      type: String,
      default: ""
    }
  },
  components: {
    baseInfo,
    purchaseList,
    uploadInfo,
    breadcrumb: publicComponent.breadcrumb
  },
  data() {
    return {
      jsList,
      breadcrumbLastItem: "",
      activeName: "first",
      isTrue: false,
      detailInfo: {}
    };
  },
  computed: {
    ...mapGetters(["getRemoveStatus"])
  },
  activated() {
    this.init();
  },
  deactivated() {
    this.activeName = "first";
    this.isTrue = false;
  },
  methods: {
    init() {
      if (this.state === "create") {
        this.detailInfo = {
          ...this.detailInfo,
          state: this.state
        };
        this.isTrue = true;
      } else {
        // 调详情接口
        this.getInventory();
      }
    },
    // 保存 提交
    async submitHandle(operType) {
      try {
        let inventoryBO,
          inventoryBOList,
          detailUploadIds,
          otherUploadIds,
          inventoryBODelList;
        const { baseInfo, purchaseList, uploadInfo } = this.$refs;
        if (operType === 3) {
          inventoryBO = baseInfo.form;
          inventoryBOList = purchaseList.tableList;
        } else {
          inventoryBO = await baseInfo.handleSubmit();
          inventoryBOList = await purchaseList.handleSubmit();
          await uploadInfo.handleSubmit();
        }
        inventoryBODelList = purchaseList.listTableData.filter(
          item => !item.flag
        );

        if (inventoryBOList.length) {
          inventoryBOList = inventoryBOList.map((item, index) => ({
            ...item,
            sn: index
          }));
        }

        // 附件上传
        detailUploadIds = this.setUploadList(uploadInfo.inventoryDetailFiles);
        otherUploadIds = this.setUploadList(uploadInfo.inventoryOtherFiles);
        // 盘点校验
        checkStockIsChange({
          warehouseId: inventoryBO.warehouseId,
          list: inventoryBOList
        }).then(res => {
          const { code, message } = res.data;

          if (code === "0") {
            const data = {
              inventoryBO,
              inventoryBOList,
              detailUploadIds,
              otherUploadIds,
              inventoryBODelList: this.getRemoveStatus
                ? inventoryBODelList
                : [],
              operType
            };

            (operType === 3
              ? tsInventory
              : this.state === "create"
              ? savInventory
              : editInventory)(data).then(res => {
              const { code, message } = res.data;
              if (code === "0") {
                this.$message.success(message);
                this.handleBack();
              }
            });
          } else {
            this.$showErrorMessage(message);
          }
        });
      } catch (error) {
        this.activeName = error;
        if (["first"].includes(error)) {
          this.$nextTick(() => {
            const errorFormEl = document.body.querySelector(".is-error");
            const errorText = errorFormEl.firstChild.innerText;
            const messageText = errorText.substring(
              0,
              errorText.lastIndexOf("：")
            );
            this.$showErrorMessage(`${messageText}未填写，请编辑后保存`);
            if (errorFormEl) {
              errorFormEl.scrollIntoView({
                behavior: "smooth", // 平滑过渡
                block: "start" // 上边框与视窗顶部平齐。默认值
              });
            }
          });
        }
      }
    },
    // 查询详情
    getInventory() {
      getInventory({ id: +this.$route.params.id }).then(res => {
        this.detailInfo = res.data.data;
        this.detailInfo = {
          ...this.detailInfo,
          state: this.state
        };
        this.breadcrumbLastItem = this.detailInfo.inventoryBO.inventoryName;
        this.setBusinessList(this.detailInfo.inventoryBO.warehouseId);
        this.setInventoryStatus(!!this.detailInfo.inventoryBO.warehouseId);

        this.isTrue = true;
      });
    },
    handleBack() {
      this.activeName = "first";
      this.$router.go(-1);
      this.reset();
      this.isTrue = false;
    },

    setUploadList(arr) {
      return arr.length
        ? arr.map((n, i) => ({
            sn: i,
            uploadTime: n.uploadTime || n.createTime || n.createTimeStr,
            fileDesc: n.fileDesc,
            fileType: n.fileType,
            uploadId: n.uploadId || n.fileInfoId
          }))
        : [];
    },

    ...mapActions(["setInventoryStatus", "setBusinessList", "reset"])
  }
};
</script>

<style scoped lang="scss">
.el-tabs__customize {
  padding-bottom: 50px;
}
</style>
